//
//  main.m
//  FindDuplicates
//
//  Created by Petur Ingi Egilsson on 8/15/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "P13File.h"
#import "P13MD5File.h"

int main (int argc, const char * argv[])
{

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    NSArray *args = [[NSProcessInfo processInfo] arguments];
    BOOL isDir;
    
    NSMutableArray *files = [NSMutableArray array];
    NSDirectoryEnumerator *dirEnum;
    NSFileManager *fm = [NSFileManager defaultManager];
    
    // Check to see if one argument has been passed (first arg is the ps name)
    if ([args count] != 2)
    {
        NSLog(@"Usage: %@ dir", [[NSProcessInfo processInfo] processName]);
        return 1;
    }
    
    // Confirm that the argument is indeed a directory
    [[NSFileManager defaultManager] fileExistsAtPath:[args objectAtIndex:1] isDirectory:&isDir];
    if (!isDir)
    {
        NSLog(@"%@ is not a directory", [args objectAtIndex:1]);
        return 2;
    }
    
    dirEnum = [fm enumeratorAtPath:[args objectAtIndex:1]];
    NSString *path;
    isDir = NO; // assume not a directory for first run
    while ((path = [dirEnum nextObject] ) != nil)
    {
        [fm fileExistsAtPath:[[args objectAtIndex:1] stringByAppendingPathComponent:path] isDirectory:&isDir];
        if (!isDir)
            [files addObject:[[P13File alloc] initWithPath:[[args objectAtIndex:1] stringByAppendingPathComponent:path]]];
        //assume not a directory for next run
        isDir = NO;
    }

    // Flokka files array eftir filesize
    [files sortUsingComparator:^NSComparisonResult(id obj1, id obj2)
     {
         unsigned long long size1, size2;
         size1 = [obj1 getSize];
         size2 = [obj2 getSize];
         if (size1 == size2) {
             return NSOrderedSame;
         }
         else if (size1 > size2)
             return NSOrderedDescending;
         else return NSOrderedAscending;
     }];
    
    // Fjarlæga allt sem er ekki af sömu stærð og annar object
    for (int counter = 0; counter < [files count]; counter++)
    {
        BOOL remove = YES; //assume object is to be removed
        P13File *obj = [files objectAtIndex:counter];
        for (int i = 0; i < [files count]; i++)
        {
            if (counter == i)
                continue;
            else if ([obj getSize] == [[files objectAtIndex:i] getSize])
                    remove = NO;
        }
        if (remove)
        {
            [files removeObjectAtIndex:counter];
            counter--;
  
        }
    }
    
    // Fjarlægja allt sem er af stærð 0
    for (int counter = 0; counter < [files count]; counter++)
        if ([[files objectAtIndex:counter] getSize] == 0)
            [files removeObjectAtIndex:counter--];
    
    // finna MD5
    for (int counter = 0; counter < [files count]; counter++)
        [[files objectAtIndex:counter] calculateMD5];
    
    // flokka eftir MD5
    [files sortUsingComparator:^NSComparisonResult(id obj1, id obj2)
     {
         NSString *s1, *s2;
         s1 = [obj1 getMD5];
         s2 = [obj2 getMD5];
         return [s1 compare:s2];
     }];
    
    // Fjarlæga allt sem er ekki af sömu MD5 og annar object
    for (int counter = 0; counter < [files count]; counter++)
    {
        BOOL remove = YES; //assume object is to be removed
        P13File *obj = [files objectAtIndex:counter];
        for (int i = 0; i < [files count]; i++)
        {
            if (counter == i)
                continue;
            else if ([[obj getMD5]compare:[[files objectAtIndex:i]getMD5]] == NSOrderedSame)
                remove = NO;
        }
        if (remove)
        {
            [files removeObjectAtIndex:counter];
            counter--;
        }
    }
    
    //DEBUG ONLY, PRINT OUT WHOLE ARRAY
    NSFileHandle *console = [NSFileHandle fileHandleWithStandardOutput];
    NSData *outputBuffer;
    NSString *seperator = @"";
    for (int i = 0; i < [files count]; i++)
    {
        if ([seperator compare:[[files objectAtIndex:i] getMD5]] != NSOrderedSame)
        {
            seperator = [NSString stringWithString:[[files objectAtIndex:i] getMD5]];
            outputBuffer = [[NSString stringWithString:@"====================================\n"]dataUsingEncoding:NSUTF8StringEncoding];
            [console writeData:outputBuffer];
        }
        outputBuffer = [[NSString stringWithFormat:@"%@\n",[[files objectAtIndex:i] getPath]] dataUsingEncoding:NSUTF8StringEncoding];
        [console writeData:outputBuffer];
    }
    
    [pool drain];
    return 0;
}

